import {
  Controller,
  Logger,
  Post,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { ApiBody, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger';
import { OpenApiService } from './open-api.service';
import { FileInterceptor } from '@nestjs/platform-express';
import dayjs from 'dayjs';
import { ImgUpload, uploadFiles, videoUpload } from './open-api.dto';
import { contentTypes, parseChineseText } from './open-api.utils';
import { log } from 'console';
import { Code } from 'src/global-type';
import { resolve } from 'path';
import { existsSync, mkdirSync, writeFileSync } from 'fs';
// const formattedDate = dayjs().format('YYYY-MM-DD');
// const formaDate =
//   dayjs().format('YYYY-MM-DDTHH:mm:ssSSZ[Z]');
@Controller('api/open-api')
@ApiTags('公共api开发')
export class OpenApiController {
  private readonly logger = new Logger(OpenApiController.name);
  constructor(private readonly openApiService: OpenApiService) { }

  @ApiBody({ type: ImgUpload })
  @Post('upload/Img')
  @ApiConsumes('multipart/form-data')
  @UseInterceptors(
    //使用FileInterceptor() 完成文件的上传
    FileInterceptor('file', {
      //这里直接就把文件上传了，我这边要压缩一下再上传
      // storage: diskStorage({
      //   destination: `images/${formattedDate}`,   //上传的位置
      //   filename: (req, file, cb) => {
      //     const randomName = Array(32)
      //       .fill(null)
      //       .map(() => Math.round(Math.random() * 16).toString(16))
      //       .join('');
      //     return cb(null, `${randomName}${extname(file.originalname)}`);
      //   },
      // }),
      fileFilter: (req, file, cb) => {
        // 进行文件过滤的逻辑
        // 这里可以根据文件类型、大小等进行验证
        if (
          file.mimetype == 'image/jpeg' ||
          file.mimetype == 'image/jpg' ||
          file.mimetype == 'image/png'
        ) {
          cb(null, true);
        }
        // 返回错误信息给客户端
        else {
          cb(new Error('仅支持jpeg/jpg/png类型的图片'), false);
        }
      },
    }),
  )
  @ApiOperation({ summary: '上传图片' })
  // @ReqType(MODULETYPE, AuthItem.READ)
  async queryLogisticsList(@UploadedFile() file: Express.Multer.File) {
    try {
      const fileName = parseChineseText(file.originalname, 'latin1');
      let size: number;
      const filePath = `/root/assets/img/`; //如果不是运行在服务器中则需要使用FTP或者SFTP来完成
      this.openApiService.imgCompress(file).then((res) => {
        size = res.size
        this.openApiService.saveFileToServer(
          filePath,
          res.compressedFile,
          fileName,
        );
      });
      return {
        message: '图片上传成功',
        data: { url: process.env.DEPLOY_URL + `/${filePath}/${fileName}`, size },
        code: Code.OK
      };
    } catch (err) {
      this.logger.error(err);
      return {
        message: String(err),
      };
    }
  }

  @Post('upload/Video')
  @ApiBody({ type: videoUpload })
  @ApiConsumes('multipart/form-data')
  @UseInterceptors(FileInterceptor('file', {
    fileFilter: (req, file, cb) => {
      // 进行文件过滤的逻辑
      // 这里可以根据文件类型、大小等进行验证
      if (
        file.mimetype == 'video/avi' ||
        file.mimetype == 'video/mpg' ||
        file.mimetype == 'video/mpeg' ||
        file.mimetype == 'video/mp4'
      ) {
        cb(null, true);
      }
      // 返回错误信息给客户端
      else {
        cb(new Error('仅支持avi/mpg/mpeg/mp4类型的视频'), false);
      }
    }
  }))
  @ApiOperation({ summary: '上传视频' })
  async uploadVideo(
    @UploadedFile() file: Express.Multer.File,
  ): Promise<any> {
    try {
      const filePath = `/root/assets/video`; //如果不是运行在服务器中则需要使用FTP或者SFTP来完成
      const fileName = parseChineseText(file.originalname, 'latin1');
      await this.openApiService.saveFileToServer(
        filePath,
        file.buffer,
        fileName,
      )
      return {
        message: '视频上传成功',
        data: { url: process.env.DEPLOY_URL + `/${filePath}/${fileName}` },
        code: Code.OK
      };
    } catch (err) {
      this.logger.error(err);
      return {
        message: String(err),
      };
    }
  }

  @Post('upload/Model')
  @ApiBody({ type: videoUpload })
  @ApiConsumes('multipart/form-data')
  @UseInterceptors(FileInterceptor('file', {
    fileFilter: (req, file, cb) => {
      // 进行文件过滤的逻辑
      // 这里可以根据文件类型、大小等进行验证
      if (
        contentTypes?.includes(file.mimetype)
      ) {
        cb(null, true);
      }
      // 返回错误信息给客户端
      else {
        cb(new Error('请上传正确的模型'), false);
      }
    }
  }))
  @ApiOperation({ summary: '上传模型' })
  async uploadModel(
    @UploadedFile() file: Express.Multer.File,
  ): Promise<any> {
    try {
      const filePath = `/root/assets/model`; //如果不是运行在服务器中则需要使用FTP或者SFTP来完成
      const fileName = parseChineseText(file.originalname, 'latin1');
      // await this.openApiService.modelCompress(file.buffer).then(async (res) => {
      //   console.log('res', res);
      //   if (res) {
      //     await this.openApiService.saveFileToServer(
      //       filePath,
      //       file.buffer,
      //       fileName,
      //     )
      //   }
      // })
      await this.openApiService.saveFileToServer(
        filePath,
        file.buffer,
        fileName);
      return {
        message: '模型上传成功',
        data: { url: process.env.DEPLOY_URL + `/${filePath}/${fileName}` },
        code: Code.OK
      };
    } catch (err) {
      this.logger.error(err);
      return {
        message: String(err),
      };
    }
  }

  @Post('uploadFiles')
  @ApiConsumes('multipart/form-data')
  @ApiBody({ type: uploadFiles })
  @UseInterceptors(
    FileInterceptor('file', {
      fileFilter: (req, file, cb) => {
        // 进行文件过滤的逻辑
        // 这里可以根据文件类型、大小等进行验证
        if (
          file.mimetype ==
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          file.mimetype == 'application/vnd.ms-excel' ||
          file.mimetype == 'text/csv'
        ) {
          cb(null, true);
        }
        // 返回错误信息给客户端
        else {
          cb(new Error('仅支持xlsx/xls/csv类型的表格'), false);
        }
      },
    }),
  )
  @ApiOperation({ summary: '上传文件输出表格' })
  async excelUpload(@UploadedFile() file: any) {
    try {
      const { originalname } = file;
      const uploadDir = resolve(__dirname, '../../files/upload');
      if (!existsSync(uploadDir)) {
        mkdirSync(uploadDir, { recursive: true });
      }
      const fileName = parseChineseText(originalname, 'latin1');
      const excelPath = uploadDir + '/' + fileName;
      const excelUrl = '../../files/upload/' + fileName;
      writeFileSync(excelPath, file.buffer, {
        encoding: 'utf8',
        flag: 'w+',
      });
      return {
        code: Code.OK,
        message: 'success',
        data: excelUrl,
      };
    } catch (err) {
      this.logger.error(err);
      return {
        code: Code.UNKNOW_ERROR,
        message: String(err),
        data: {
          total: 0,
          data: [],
        },
      };
    }
  }
}
